package com.xxrl.shop.controller;


import com.xxrl.shop.common.entity.JsonResult;
import com.xxrl.shop.common.utils.PageTool;
import com.xxrl.shop.common.utils.ResultTool;
import com.xxrl.shop.domain.Merchant;
import com.xxrl.shop.domain.Order;
import com.xxrl.shop.domain.Product;
import com.xxrl.shop.domain.User;
import com.xxrl.shop.service.CartService;
import com.xxrl.shop.service.MerchantService;
import com.xxrl.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author mis
 */
@Api(tags = {"order"})
@RestController
@RequestMapping("/order")
public class OrderController {

    private final OrderService orderService;
    private final CartService cartService;
    private final MerchantService merchantService;

    public OrderController(OrderService orderService, CartService cartService, MerchantService merchantService) {
        this.orderService = orderService;
        this.cartService = cartService;
        this.merchantService = merchantService;
    }
    /**
     * 管理员 列出所有的订单
     * @param page 页号
     * @param size 页长
     * @return Json数据
     */
    @ApiOperation(value = "List all orders by page request.", response = Order.class, responseContainer = "List")
    @GetMapping("manageList")
    public JsonResult<String> managerList(@RequestParam(defaultValue = "0", name = "page")Integer page,
                                          @RequestParam(defaultValue = "10", name = "size")Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<Order> orders = orderService.listOrder(pageRequest);
        return ResultTool.success(PageTool.pageToJson(orders));
    }

    /**
     * 商家的订单
     * @param page 页号
     * @param size 页长
     * @param userId 用户id
     * @return Json数据
     */
    @ApiOperation(value = "List all orders of merchant by page request.", response = Order.class, responseContainer = "List")
    @GetMapping("merchantList")
    public JsonResult<String> merchantList(@RequestParam(defaultValue = "0", name = "page")Integer page,
                                           @RequestParam(defaultValue = "10", name = "size")Integer size,
                                           @RequestParam(name = "userId") Long userId) {
        PageRequest pageRequest = PageRequest.of(page,size);
        Merchant merchant = merchantService.getMerchantByUser(new User(userId));
        Page<Order> orders = orderService.getOrderByMerchant(merchant, pageRequest);
        return ResultTool.success(PageTool.pageToJson(orders));
    }
    /**
     * 商品的订单
     * @param page 页号
     * @param size 页长
     * @param productId 商品id
     * @return Json数据
     */
    @ApiOperation(value = "List all orders of product by page request.", response = Order.class, responseContainer = "List")
    @GetMapping("productList")
    public JsonResult<String> productList(@RequestParam(defaultValue = "0", name = "page") Integer page,
                                          @RequestParam(defaultValue = "10", name = "size") Integer size,
                                          @RequestParam(defaultValue = "false") Boolean withComment,
                                          @RequestParam(defaultValue = "0") Long timeAfter,
                                          @RequestParam(name = "productId") Long productId) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<Order> orders;
        if (withComment) {
            orders = orderService.getOrderWithCommentByProduct(new Product(productId), pageRequest);
        } else if (timeAfter != 0) {
            orders = orderService.getOrderAfterDateByProduct(new Product(productId), new Date(timeAfter), pageRequest);
        } else {
            orders = orderService.getOrderByProduct(new Product(productId), pageRequest);
        }
        return ResultTool.success(PageTool.pageToJson(orders));
    }

    /**
     * 用户 列出自己的订单
     * @param page 页号
     * @param size 页长
     * @param userId 用户id
     * @return Json数据
     */
    @ApiOperation(value = "List all orders of user by page request.", response = Order.class, responseContainer = "List")
    @GetMapping("list")
    public JsonResult<String> list(@RequestParam(defaultValue = "0", name = "page")Integer page,
                                   @RequestParam(defaultValue = "10", name = "size")Integer size,
                                   @RequestParam(name = "userId") Long userId) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<Order> orders = orderService.getOrderByUser(new User(userId), pageRequest );
        return ResultTool.success(PageTool.pageToJson(orders));
    }

    @ApiOperation(value = "Insert a new order.", response = Integer.class)
    @PostMapping("add")
    public JsonResult<Long> add(@RequestParam(name = "productId") Long productId,
                                @RequestParam(name = "addressId") Long addressId,
                                @RequestParam(name = "userId") Long userId,
                                @RequestParam(name = "productNum", defaultValue = "1") Integer num) {
        cartService.deleteCart(userId, productId);
        Long orderId = orderService.addOrder(productId, userId, addressId, num);
        return ResultTool.success(orderId);
    }

    @ApiOperation(value = "Insert a new order.")
    @PostMapping("payment")
    public JsonResult<String> payment(@RequestParam(name = "orderId") Long orderId) {
        // 直接修改订单状态 没有调用支付接口
        orderService.updateOrderStatus(orderId,"已支付");
        return ResultTool.success();
    }

    @ApiOperation(value = "Update order status to ship.")
    @PostMapping("ship")
    public JsonResult<String> ship(@RequestParam(name = "orderId") Long orderId) {
        orderService.updateOrderStatus(orderId,"已发货");
        return ResultTool.success();
    }

    @ApiOperation(value = "Update order status to receive.")
    @PostMapping("receive")
    public JsonResult<String> receive(@RequestParam(name = "orderId") Long orderId) {
        orderService.updateOrderStatus(orderId,"已收货");
        return ResultTool.success();
    }

    @ApiOperation(value = "Save rate and comment of order.")
    @PostMapping("ratings")
    public JsonResult<String> ratings(@RequestParam(name = "id") Long orderId,
                                      @RequestParam(name = "ratings", defaultValue = "5") Double rating,
                                      @RequestParam(name = "comment", defaultValue = "no comment") String comment) {
        orderService.saveComment(orderId, rating, comment);
        return ResultTool.success();
    }

    @ApiOperation(value = "Update order info.")
    @PostMapping("edit")
    public JsonResult<String> edit(Order order) {
        orderService.saveOrder(order);
        return ResultTool.success("OK");
    }

    @ApiOperation(value = "Remove order.")
    @PostMapping("delete")
    public JsonResult<String> delete(@RequestParam(name = "orderId") Long orderId) {
        orderService.removeOrder(orderId);
        return ResultTool.success("OK");
    }
}
